/*!
 * Page: mine/add-user-verification/AddUserVerification
 * License: MIT
 * Created: 2019-09-18 15:18
 */

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { uploadFile } from '/api/file'
import { userApi } from '/api/user'
import { getDomoUser } from '/store/actions'
import { getServer } from '/store/mutations'
import { GlobalData } from '/store/state'

Page({
  data: {
    isFullScreen: GlobalData.isFullScreen,
    form: {
      type: 'org',
      data: {
        org: {
          name: '' as string, // 机构名称
          address: '', //机构地址
          certificate: '', // 企业证书
        },
        person: {
          number: '',
          name: '',
        },
        phone_number: '', // 手机号码
        desc: '',
      },
    } as UpdateVerificationOrgPayload,
    submitting: false as boolean,
    canSubmit: false as boolean,
    certificate: '' as string,
    certificateTmp: '' as string,
    show: false,
    imageParams: {
      width: 297,
      height: 420,
      max_width: 594,
      max_height: 840,
      export_scale: 1,
      disable_rotate: true,
      disable_ratio: true,
      limit_move: true,
      src: '' as string,
      show: false,
      scale: 0.7,
    },
    cropper: '' as any,
    update: false,
    /** 是否是重新认证 */
    reVeiryfied: false,
  },
  onLoad(query) {
    this.setData({
      isFullScreen: GlobalData.isFullScreen,
      reVeiryfied: query.isReVeiryfied as unknown as boolean,
    })
    if (query.load) {
      this.getUserInfo()
    }
  },
  /** 取消选择图片 */
  cancel() {
    this.setData({
      show: false,
    })
  },
  getUserInfo() {
    const server = getServer()
    const user = wx.getStorageSync(`${server}/logged`).data || {}
    this.setData({
      form: {
        type: 'org',
        data: {
          org: {
            address: user.verification.org.address,
            certificate: user.verification.org.certificate.node,
            name: user.verification.org.name,
          },
          person: user.verification.person,
          phone_number: user.verification.phone_number,
          desc: user.verification.desc,
        },
      },
      certificate: '',
      certificateTmp: '',
      update: true,
      canSubmit: true,
      verification: user.verification,
    })
  },
  /** 初始化裁剪 */
  onShow() {
    this.setData({
      // @ts-ignore
      cropper: this.selectComponent('#certificate-cropper'),
    })
  },
  /** 检测输入框变化 */
  handleConfirm({
    detail: { value },
    target: {
      dataset: { type },
    },
  }: {
    detail: any
    target: any
    type: string
  }) {
    switch (type) {
      case 'org_name':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                org: {
                  ...this.data.form.data.org,
                  name: value,
                },
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'address':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                org: {
                  ...this.data.form.data.org,
                  address: value,
                },
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'person_name':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                person: {
                  ...this.data.form.data.person,
                  name: value,
                },
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'phone_number':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                phone_number: value,
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'desc':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                desc: value,
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
      case 'identify':
        this.setData(
          {
            form: {
              ...this.data.form,
              data: {
                ...this.data.form.data,
                person: {
                  ...this.data.form.data.person,
                  number: value,
                },
              },
            },
          },
          () => {
            this.computeCanSubmit()
          },
        )
        break
    }
  },
  /** 裁剪预览 */
  clickcut(e: any) {
    //图片预览
    wx.previewImage({
      current: e.detail.url, // 当前显示图片的http链接
      urls: [e.detail.url], // 需要预览的图片http链接列表
    })
  },
  /** 选择裁剪的图片 */
  submitFront() {
    this.data.cropper.getImg((obj: any) => {
      this.setData(
        {
          show: false,
          certificateTmp: obj.url,
        },
        () => {
          this.computeCanSubmit()
        },
      )
    })
  },
  /** 检测提交按钮是否被禁用 */
  computeCanSubmit() {
    const {
      phone_number,
      desc,
      person: { name: person_name, number },
      org: { address, name, certificate },
    } = this.data.form.data
    const {
      data: { certificateTmp },
    } = this
    this.setData({
      canSubmit: !!(
        phone_number &&
        address &&
        name &&
        desc &&
        person_name &&
        number &&
        (certificateTmp || certificate)
      ),
    })
  },
  /** 选择图片 */
  handleBgTap() {
    wx.chooseImage({
      success: ({ tempFilePaths: { [0]: path } }) => {
        this.setData({
          imageParams: {
            ...this.data.imageParams,
            src: path,
          },
          show: true,
        })
      },
    })
  },
  /** 上传 */
  async doSubmit() {
    const { certificateTmp, form, update } = this.data

    const _IDRe18 =
      /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/

    // 校验身份证：
    if (_IDRe18.test(form.data.person.number) || _IDre15.test(form.data.person.number)) {
      console.log('验证通过')
    } else {
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: 'none',
        duration: 2000,
      })
      return
    }

    let {
      data: { certificate },
    } = this
    this.setData({
      submitting: true,
    })
    try {
      if (!certificate && !update) {
        if (!certificateTmp) {
          // 没有选择文件
          wx.showToast({
            title: '请选择要上传的文件',
            icon: 'none',
          })
          return
        }
        certificate = await uploadFile(certificateTmp)
        form.data.org.certificate = certificate
        this.setData({ certificate })
      } else {
        // 重新认证
        if (certificateTmp) {
          // 如果检测到有临时文件，则上传
          certificate = await uploadFile(certificateTmp)
          form.data.org.certificate = certificate
          this.setData({ certificate })
        }
      }
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }
    const method = update ? 'updateVerification' : 'saveVerification'

    // 重新认证，需要吸纳删除以前的认证
    if (this.data.reVeiryfied) {
      await userApi.deleteVerification()
    }
    userApi[method](form)
      .then(() => {
        this.setData(
          {
            submitting: false,
          },
          () => {
            wx.showToast({
              title: '成功，待审核',
              duration: 1500,
            })
            getDomoUser()
            setTimeout(() => {
              wx.switchTab({
                url: '/pages/user/user',
              })
            }, 1500)
          },
        )
      })
      .catch((data: { data: {} }) => {
        this.setData(
          {
            submitting: false,
          },
          () => {
            wx.showToast({ title: `${getMessage(data.data).getMessage()}`, icon: 'none' })
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/user/user',
              })
            }, 1500)
          },
        )
      })
  },
})
